<template>
  <div class="project-cats-container">
    <div class="main-card">
      <!-- 页面标题 -->
      <div class="card-header">
        <h2 class="card-title">项目分类管理</h2>
      </div>
      
      <div class="search-section">
        <div class="search-container">
          <div class="search-item">
            <span class="search-label">分类名称</span>
            <el-input v-model="queryParams.keyword" placeholder="请输入分类名称" clearable @keyup.enter="handleQuery"
              class="search-input">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </div>
          <div class="search-buttons">
            <el-button type="primary" @click="handleQuery" :icon="Search">查询</el-button>
            <el-button @click="resetQuery" :icon="RefreshRight">重置</el-button>
          </div>
        </div>
      </div>

      <!-- 工具栏 -->
      <div class="table-toolbar">
        <el-button type="primary" @click="handleAdd" :icon="Plus">新增分类</el-button>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table :data="tableData" fit v-loading="loading" border stripe highlight-current-row
          :cell-style="{ textAlign: 'center' }">
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column label="分类名称" align="center">
            <template #default="{ row }">
              <el-tag
                :type="getRandomTagType(row.id)"
                :effect="getRandomEffect(row.id)"
                class="tag-item"
              >
                {{ row.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="分类描述" align="center"/>
          <el-table-column prop="createTime" label="创建时间" align="center"/>
          <el-table-column prop="updateTime" label="更新时间" align="center" />
          <el-table-column label="操作" align="center" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)" class="action-button">
                <el-icon>
                  <Edit />
                </el-icon>
                <span>编辑</span>
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)" class="action-button">
                <el-icon>
                  <Delete />
                </el-icon>
                <span>删除</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]" background layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <!-- 分类编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" destroy-on-close>
      <el-form v-if="formData" :model="formData" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
          <div class="form-tip">请输入分类名称，最多50个字符</div>
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入分类描述" />
          <div class="form-tip">请输入分类描述，最多200个字符</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { debounce } from 'lodash-es'
import { Search, RefreshRight, Edit, Delete, Plus } from '@element-plus/icons-vue'
import { getProjectCategoryPageList, getProjectCategoryById, saveProjectCategory, deleteProjectCategoryById } from '@/api/projectCategory'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'

// 查询参数
const queryParams = reactive({
  keyword: '',
  pageNum: 1,
  pageSize: 10
})

// 数据列表
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 编辑相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增分类')
const formData = ref(null)
const formRef = ref(null)
const submitLoading = ref(false)

// 标签类型和效果
const tagTypes = ['primary', 'success', 'warning', 'danger', 'info']
const tagEffects = ['light', 'dark', 'plain']

// 根据ID获取随机但固定的标签类型
const getRandomTagType = (id) => {
  return tagTypes[id % tagTypes.length]
}

// 根据ID获取随机但固定的标签效果
const getRandomEffect = (id) => {
  return tagEffects[id % tagEffects.length]
}

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入分类描述', trigger: 'blur' },
    { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
  ]
}

// 防抖处理查询
const debouncedQuery = debounce(() => {
  getList()
}, 300)

// 获取分类列表
const getList = async () => {
  if (loading.value) return
  loading.value = true
  try {
    const params = {
      keyword: queryParams.keyword,
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    }
    const res = await getProjectCategoryPageList(params)
    if (res.code === 200) {
      tableData.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error({
        message: res.msg || '获取分类列表失败',
        duration: 3000,
        showClose: true
      })
    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
    if (!error.code || error.code !== 403) {
      ElMessage.error({
        message: '获取分类列表出错，请稍后重试',
        duration: 3000,
        showClose: true
      })
    }
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  debouncedQuery()
}

// 重置按钮
const resetQuery = () => {
  queryParams.keyword = ''
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  debouncedQuery()
}

// 页码变化
const handleCurrentChange = (current) => {
  queryParams.pageNum = current
  debouncedQuery()
}

// 新增分类
const handleAdd = () => {
  dialogTitle.value = '新增分类'
  formData.value = {
    name: '',
    description: ''
  }
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = async (row) => {
  dialogTitle.value = '编辑分类'
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载分类信息...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const res = await getProjectCategoryById(row.id)
    if (res.code === 200) {
      formData.value = {
        id: res.data.id,
        name: res.data.name,
        description: res.data.description
      }
      dialogVisible.value = true
    } else {
      ElMessage.error({
        message: res.msg || '获取分类详情失败',
        duration: 3000,
        showClose: true
      })
    }
  } catch (error) {
    if (!error.code || error.code !== 403) {
      ElMessage.error({
        message: '获取分类详情出错，请稍后重试',
        duration: 3000,
        showClose: true
      })
    }
  } finally {
    loading.close()
  }
}

// 删除分类
const handleDelete = async (row) => {
  ElMessageBox.confirm(
    `确定要删除分类「${row.name}」吗？此操作不可逆。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const loading = ElLoading.service({
      lock: true,
      text: '正在删除...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      const res = await deleteProjectCategoryById(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList() // 刷新列表
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      if (!error.code || error.code !== 403) {
        ElMessage.error('删除失败，请稍后重试')
      }
    } finally {
      loading.close()
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    submitLoading.value = true
    try {
      const saveData = { ...formData.value }
      
      const res = await saveProjectCategory(saveData)
      if (res.code === 200) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        getList() // 刷新列表
      } else {
        ElMessage.error(res.msg || '保存失败')
      }
    } catch (error) {
      if (!error.code || error.code !== 403) {
        ElMessage.error('保存失败，请稍后重试')
      }
    } finally {
      submitLoading.value = false
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.project-cats-container {
  min-height: calc(100vh - 120px);
  background-color: #f5f7fa;
}

.main-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.card-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin: 0;
  line-height: 1.5;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.search-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.search-label {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.search-input {
  width: 220px;
}

.search-buttons {
  display: flex;
  gap: 10px;
  margin-top: 24px;
}

.table-toolbar {
  padding: 0 20px 10px;
  display: flex;
  justify-content: flex-start;
}

.table-section {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  width: 100%;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.action-button {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
}

.action-button .el-icon {
  font-size: 16px;
}

.tag-item {
  padding: 4px 8px;
  margin: 0 2px;
  font-size: 14px;
  min-width: 70px;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .project-cats-container {
    padding: 10px;
  }

  .search-container {
    flex-direction: column;
    align-items: flex-start;
  }

  .search-item {
    width: 100%;
  }

  .search-input {
    width: 100%;
  }

  .search-buttons {
    width: 100%;
    margin-top: 15px;
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.5;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

:deep(.el-select) {
  width: 100%;
}
</style>